//封装请求函数(一)
import {
  axiosPost
} from '../libs/https';

//引入缓存数据文件
import s1A1DataArr from '../datas/subject1&a1';
import s1A2DataArr from '../datas/subject1&a2';
import s1B1DataArr from '../datas/subject1&b1';
import s1B2DataArr from '../datas/subject1&b2';
import s1C1DataArr from '../datas/subject1&c1';
import s1C2DataArr from '../datas/subject1&c2';

import s4A1DataArr from '../datas/subject4&a1';
import s4A2DataArr from '../datas/subject4&a2';
import s4B1DataArr from '../datas/subject4&b1';
import s4B2DataArr from '../datas/subject4&b2';
import s4C1DataArr from '../datas/subject4&c1';
import s4C2DataArr from '../datas/subject4&c2';

//引入驾照类型数据
import modelTypeName from '../configs/model';

const cacheSubject1Datas = [
    s1A1DataArr,
    s1A2DataArr,
    s1B1DataArr,
    s1B2DataArr,
    s1C1DataArr,
    s1C2DataArr
  ],
  cacheSubject4Datas = [
    s4A1DataArr,
    s4A2DataArr,
    s4B1DataArr,
    s4B2DataArr,
    s4C1DataArr,
    s4C2DataArr
  ];

//请求后端数据
function getData(options) {
  const {
    subjectId,
    modelType
  } = options;

  //为什么使用new Promise()？
  //为了可以使用async/await语法
  return new Promise((resolve, reject) => {
    //请求示例：http://v.juhe.cn/jztk/query?subject=1&model=c1&key=您申请的appKey
    axiosPost({
      //https.js > options.url:
      url: `/api/jztk/query`,
      data: {
        subject: subjectId,
        model: modelType
      },
      success(data) {
        //抛出data
        resolve(data);
      },
      error(err) {
        reject(err);
      }
    });
  });
}

//请求本地数据
function getCacheData(options) {
  const {
    subjectId,
    modelType
  } = options;

  const dataObj = {
    reason: 'ok',
    result: '',
    error_code: 0
  };

  if (subjectId === 1) {
    _mapModelTypeName(cacheSubject1Datas, subjectId, modelType, dataObj);
  } else if (subjectId === 4) {
    _mapModelTypeName(cacheSubject4Datas, subjectId, modelType, dataObj);
  }

  return dataObj;
}

function _mapModelTypeName(cacheSubjectDatas, subjectId, modelType, dataObj) {
  modelTypeName.forEach((item, index) => {
    const cacheData = cacheSubjectDatas[index];

    switch (modelType) {
      case item.type:
        console.log(`Get local cache data success! : subjectId:${subjectId} modelType: ${modelType}`);
        dataObj.result = cacheData;
        break;
      default:
        break;
    }
  });
}

export {
  getData,
  getCacheData
}